<?php

namespace app\services\office;

use app\dao\office\OfficeStudentDao;
use app\exceptions\AdminException;
use app\exceptions\AuthException;
use app\services\BaseService;
use app\utils\Token;
use hg\apidoc\annotation\Param;
use OSS\Core\OssException;
use OSS\OssClient;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\db\Where;
use think\Exception;
use think\Db;
use think\facade\Filesystem;

class OfficeStudentService extends BaseService
{
    public function __construct(OfficeStudentDao $dao)
    {
        $this->dao = $dao;
    }

    public function index(array $where)
    {
        return $this->dao->index($where);
    }

    public function create(array $where)
    {
        return $this->dao->create($where);
    }

    public function update(array $where)
    {
        return $this->dao->updateDao($where);
    }

    public function delete(array $where)
    {
        return $this->dao->deleteDao($where);
    }

    public function search(array $where)
    {
        return $this->dao->searchDao($where);

    }

    public function getUserList(array $where)
    {
        return $this->dao->getUserList($where);
    }

    public function getIdsFormUser(array $where)
    {
        return $this->dao->getIdsFormUser($where);
    }

    public function selectAllSearchToExcel(array $where)
    {
        return $this->dao->selectAllSearchToExcel($where);

    }

    /**
     * 导出学生基础信息
     * @param array $where
     * @return void
     */
    public function excelOutFromIds(array $where)
    {
        $data = $this->dao->excelOutFromIds($where);
        //设置跨域请求
        header('Access-Control-Allow-Origin: *');
        header("Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With,accessToken,website");
        header('Access-Control-Allow-Methods: GET, POST, PUT');

        $title = ['id', '专业名称','学生头像','学生姓名','性别','常住地址','邮政编码','身份证号','手机号','准考证号','入学批次','入学类型','学号','生日','政治面貌','毕业学校'];
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        //表头
        //设置单元格内容
        foreach ($title as $key => $value) {
            // 单元格内容写入
            $sheet->setCellValueByColumnAndRow($key + 1, 1, $value);
        }
        $row = 2; // 从第二行开始
        foreach ($data as $val) {
            $sheet->setCellValueByColumnAndRow(1, $row, $val['id']);
            $sheet->setCellValueByColumnAndRow(2, $row, $val['majors'] ? $val['majors']['title'] : '');
            $sheet->setCellValueByColumnAndRow(3, $row, $val['heard']);
            $sheet->setCellValueByColumnAndRow(4, $row, $val['name']);
            $sheet->setCellValueByColumnAndRow(5, $row, $val['sex']);
            $sheet->setCellValueByColumnAndRow(6, $row, $val['adress']);
            $sheet->setCellValueByColumnAndRow(7, $row, $val['postal_code']);
            $sheet->setCellValueByColumnAndRow(8, $row, $val['idcard']);
            $sheet->setCellValueByColumnAndRow(9, $row, $val['phone']);
            $sheet->setCellValueByColumnAndRow(10, $row, $val['exam_number']);
            $sheet->setCellValueByColumnAndRow(11, $row, $val['enter_batch']);
            $sheet->setCellValueByColumnAndRow(12, $row, $val['enter_type']);
            $sheet->setCellValueByColumnAndRow(13, $row, $val['student_number']);
            $sheet->setCellValueByColumnAndRow(14, $row, $val['birthday']);
            $sheet->setCellValueByColumnAndRow(15, $row, $val['political']);
            $sheet->setCellValueByColumnAndRow(16, $row, $val['graduated_school']);
            $row++;
        }

        // Redirect output to a client’s web browser (Xlsx)
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="学生信息表.xlsx"');//输出的文件名
        header('Cache-Control: max-age=0');
        header('Cache-Control: max-age=1');

        // If you're serving to IE over SSL, then the following may be needed
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0
        $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
        exit();

    }


//    ================================================ api ================================================================
    /*
     * 获取学生基本资料
     */
    public function getUserInformation(array $where)
    {
        return $this->dao->getUserInformation($where);

    }

    /*
     * 修改密码
     */
    public function updataPwd(array $where)
    {
        $data = $this->dao->updataPwd($where);
        if ($data) {
            return '修改成功';
        } else {
            throw new AuthException('修改失败');
        }
    }

    /*
     * 用户登录
     */
    public function register(array $where)
    {
        $data = $this->dao->register($where);
        if (!$data) throw new AuthException('没找到该用户！');
        if (!($where['pwd'] == $data['pwd'])) throw new AuthException('账号或者密码错误！');
        return Token::getToken('userId',$data['id']);
    }

    /*
     * 通过学生获取考试列表
     */
    public function getTest(array $where)
    {
        $list = $this->dao->getClassId($where);
        $where['list']=$list;
        $exam = $this->dao->getTest($where);
//        $exam=$this->dao->getExam($where);
//        for ($i=0;$i<count($data);$i++){
//            $data[$i]['UserExam']=null;
//            for ($m=0;$m<count($exam);$m++){
//                if ($data[$i]['id']==$exam[$m]['exam_id']){
//                    $exam[$m]['status']='未完成';
//                    if ($exam[$m]['total_score']>60){
//                        $exam[$m]['status']='已完成';
//                    }
//                    $data[$i]['UserExam']=$exam[$m];
//                }
//            }
//        }

        for ($i=0;$i<count($exam);$i++){
            $where['exam_id'] = $exam[$i]['id'];
            $where['classid'] = $exam[$i]['class_id'];
            $data = $this->dao->getExam($where);
            $exam[$i]['exam_num']=$exam[$i]['exam_num']-count($data);
        }
        $sbject['exam']=$exam;
        $sbject['other'] = ['phone' => '18523171336'];
//        $sbject['record']=$exam;
        return $sbject;

    }
    /*
     * 获取测试成绩
     */

    public function getExamRecord(array $where){
        $list = $this->dao->getClassId($where);
        $where['list']=$list;
        $exam=$this->dao->getExamRecord($where);
        return $exam;
    }
    public function info(array $where)
    {
        if (!Token::verifyToken($where['jwt'])) throw new AuthException('参数不合法！');
        $where['userId'] = Token::getUserId($where['jwt'],'userId');
        return $this -> dao -> info($where);
    }




}